//
//  TrackListDetailViewController.m
//  瓜子电台
//
//  Created by lanou on 16/8/10.
//  Copyright © 2016年 YueZhang. All rights reserved.
//

#import "TrackListDetailViewController.h"
#import "XiaoBianMoreDetailModel.h"
#import "AuthorInfoModel.h"
#import "PlayListModel.h"
#import "PlayListTableViewCell.h"
#import "MusicPlayerViewController.h"

@interface TrackListDetailViewController ()

@property (nonatomic, strong) XiaoBianMoreDetailModel *moreDetailModel;

@property (nonatomic, strong) AuthorInfoModel *authorInfoModel;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, assign) NSInteger pageId;

@property (nonatomic, assign) NSInteger maxPageId;

@end

@implementation TrackListDetailViewController

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"PlayListTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell_1"];
    self.title = self.model.title;
    [self requestData1];
    [self requestData2];
    [self setHeaderView];
    [self headerAndFooter];
}

- (void)requestData1
{
    NSString *url = @"http://mobile.ximalaya.com/mobile/v1/album/detail?albumId=266276&device=iPhone&statEvent=pageview%2Falbum%40266276&statModule=%E5%B0%8F%E7%BC%96%E6%8E%A8%E8%8D%90&statPage=tab%40%E5%8F%91%E7%8E%B0_%E6%8E%A8%E8%8D%90&statPosition=1";
    NSString *detailUrl = [url stringByReplacingOccurrencesOfString:@"albumId=266276" withString:[NSString stringWithFormat:@"albumId=%ld",self.model.albumId]];
    [NetWorkrequestManage requestWithType:GET url:detailUrl parameters:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        [self.moreDetailModel setValuesForKeysWithDictionary:dict[@"data"][@"detail"]];
        [self.authorInfoModel setValuesForKeysWithDictionary:dict[@"data"][@"user"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } error:^(NSError *error) {
        
    }];
}

- (void)requestData2
{
    if (self.pageId == 0) {
        self.pageId = 1;
    }
    NSLog(@"%ld",self.model.albumId);
    NSString *url = [NSString new];
    if (self.pageId == 1) {
        url = @"http://mobile.ximalaya.com/mobile/v1/album?albumId=364178&device=iPhone&pageSize=20&source=5&statEvent=pageview%2Falbum%40364178&statModule=%E5%B0%8F%E7%BC%96%E6%8E%A8%E8%8D%90&statPage=tab%40%E5%8F%91%E7%8E%B0_%E6%8E%A8%E8%8D%90&statPosition=2";
    } else {
        url = @"http://mobile.ximalaya.com/mobile/v1/album/track?albumId=364178&device=iPhone&isAsc=true&pageId=2&pageSize=20&statEvent=pageview%2Falbum%40364178&statModule=%E5%B0%8F%E7%BC%96%E6%8E%A8%E8%8D%90&statPage=tab%40%E5%8F%91%E7%8E%B0_%E6%8E%A8%E8%8D%90&statPosition=2";
    }
    
    NSString *url1 = [url stringByReplacingOccurrencesOfString:@"pageId=2" withString:[NSString stringWithFormat:@"pageId=%ld", self.pageId]];
    NSString *detailUrl = [url1 stringByReplacingOccurrencesOfString:@"albumId=364178" withString:[NSString stringWithFormat:@"albumId=%ld",self.model.albumId]];
    [NetWorkrequestManage requestWithType:GET url:detailUrl parameters:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        if (self.pageId == 1) {
            self.maxPageId = [dict[@"data"][@"tracks"][@"maxPageId"] integerValue];
            for (NSDictionary *dataDic in dict[@"data"][@"tracks"][@"list"]) {
                PlayListModel *model = [[PlayListModel alloc] init];
                [model setValuesForKeysWithDictionary:dataDic];
                [self.dataArray addObject:model];
            }
        } else {
            self.maxPageId = [dict[@"data"][@"maxPageId"] integerValue];
            for (NSDictionary *dataDic in dict[@"data"][@"list"]) {
                PlayListModel *model = [[PlayListModel alloc] init];
                [model setValuesForKeysWithDictionary:dataDic];
                [self.dataArray addObject:model];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            if (self.pageId == self.maxPageId) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        });
        
    } error:^(NSError *error) {
        
    }];
}

- (void)headerAndFooter
{
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageId = 1;
        [self.dataArray removeAllObjects];
        [self requestData2];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.pageId++;
        [self requestData2];
    }];
}

- (void)setHeaderView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 140)];
    UIImageView *pic = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
    [pic sd_setImageWithURL:[NSURL URLWithString:self.model.coverMiddle] placeholderImage:[UIImage imageNamed:@"picPlaceHolder"]];
    [[pic layer] setShadowOffset:CGSizeMake(5, 5)];
    [[pic layer] setShadowRadius:2];
    [[pic layer] setShadowOpacity:0.5];
    [[pic layer] setShadowColor:[UIColor blackColor].CGColor];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(155, 90, 60, 20)];
    float a = (CGFloat)self.model.playsCounts / 10000;
    char buf[10];
    sprintf(buf, "%.1f", a);
    sscanf(buf, "%f", &a);
    NSString *str = [NSString stringWithFormat:@"%s万", buf];
    label.text = str;
    label.font = [UIFont systemFontOfSize:13];
    label.alpha = 0.5;
    [view addSubview:label];
    [view addSubview:pic];
    
    UIImageView *imgV1 = [[UIImageView alloc] initWithFrame:CGRectMake(140, 92.5, 15, 15)];
    imgV1.image = [UIImage imageNamed:@"播放镂空"];
    [view addSubview:imgV1];
    
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(140, 20, kScreenWidth - 140 - 20, 20)];
    label1.text = [NSString stringWithFormat:@"主播：%@", self.model.nickname];
    label1.font = [UIFont systemFontOfSize:13];
    label1.alpha = 0.5;
    [view addSubview:label1];
    
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(140, 55, kScreenWidth - 140 - 20, 20)];
    label2.text = self.model.intro;
    label2.font = [UIFont systemFontOfSize:13];
    label2.alpha = 0.5;
    [view addSubview:label2];
    
    self.tableView.tableHeaderView = view;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PlayListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_1" forIndexPath:indexPath];
    PlayListModel *model = self.dataArray[indexPath.row];
    [cell setDataWithModel:model];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [MyPlayerManager defaultManager].musicLists = self.dataArray;
    [MyPlayerManager defaultManager].index = indexPath.row;
    MusicPlayerViewController *vc = [[MusicPlayerViewController alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
